<template>
  <div class="order-management">
    <div class="order-header">
      <!-- <h3>订单管理</h3> -->
      <a-button @click="refreshOrders" :loading="loading" type="primary">
        刷新订单
      </a-button>
    </div>

    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane key="lessor" tab="我的出租订单">
        <div class="order-content">
          <!-- PC端表格 -->
          <a-table 
            :dataSource="lessorOrders" 
            :columns="lessorColumns" 
            size="small" 
            :pagination="false"
            :loading="loading"
            row-key="_id"
            class="desktop-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">{{ record.status }}</a-tag>
              </template>
              <template v-if="column.key === 'amount'">
                <span class="amount">¥{{ record.amount }}</span>
              </template>
              <template v-if="column.key === 'createdAt'">
                <span>{{ formatDate(record.createdAt) }}</span>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewOrder(record)">查看</a-button>
                  <a-button 
                    v-if="record.status === '待确认'" 
                    size="small" 
                    type="primary" 
                    @click="confirmOrder(record._id)"
                    :loading="confirming === record._id"
                  >
                    确认完成
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
          
          <!-- 移动端卡片 -->
          <div class="mobile-order-cards">
            <div 
              v-for="record in lessorOrders" 
              :key="record._id" 
              class="order-card"
            >
              <div class="order-card-header">
                <div class="order-id">{{ record.account?.number || '未知账号' }}</div>
                <div class="order-status">
                  <a-tag :color="getStatusColor(record.status)">{{ record.status }}</a-tag>
                </div>
              </div>
              
              <div class="order-card-content">
                <div class="order-info-row">
                  <span class="info-label">金额</span>
                  <span class="info-value amount">¥{{ record.price }}</span>
                </div>
                <div class="order-time">{{ formatDate(record.createdAt) }}</div>
              </div>
              
              <div class="order-card-actions">
                <a-button size="small" @click="viewOrder(record)">查看详情</a-button>
                <a-button 
                  v-if="record.status === '待确认'" 
                  size="small" 
                  type="primary" 
                  @click="confirmOrder(record._id)"
                  :loading="confirming === record._id"
                >
                  确认完成
                </a-button>
              </div>
            </div>
          </div>
          
          <div v-if="lessorOrders.length === 0 && !loading" class="empty-state">
            <a-empty description="暂无出租订单" />
          </div>
        </div>
      </a-tab-pane>
      
      <a-tab-pane key="tenant" tab="我的租赁订单">
        <div class="order-content">
          <!-- PC端表格 -->
          <a-table 
            :dataSource="tenantOrders" 
            :columns="tenantColumns" 
            size="small" 
            :pagination="false"
            :loading="loading"
            row-key="_id"
            class="desktop-table"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">{{ record.status }}</a-tag>
              </template>
              <template v-if="column.key === 'depositStatus'">
                <a-tag v-if="record.depositRefunded || record.status === '已退款'" color="green">已退还</a-tag>
                <a-tag v-else-if="record.status === '已完成'" color="orange">押金未退</a-tag>
                <a-tag v-else color="blue">冻结中</a-tag>
              </template>
              <template v-if="column.key === 'createdAt'">
                <span>{{ formatDate(record.createdAt) }}</span>
              </template>
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button size="small" @click="viewOrder(record)">查看</a-button>
                  <a-button 
                    v-if="record.status === '进行中'" 
                    size="small" 
                    type="primary" 
                    @click="completeOrder(record._id)"
                    :loading="completing === record._id"
                  >
                    完成订单
                  </a-button>
                </a-space>
              </template>
            </template>
          </a-table>
          
          <!-- 移动端卡片 -->
          <div class="mobile-order-cards">
            <div 
              v-for="record in tenantOrders" 
              :key="record._id" 
              class="order-card"
            >
              <div class="order-card-header">
                <div class="order-id">{{ record.account?.number || '未知账号' }}</div>
                <div class="order-status">
                  <a-tag :color="getStatusColor(record.status)">{{ record.status }}</a-tag>
                </div>
              </div>
              
              <div class="order-card-content">
                <div class="order-info-row">
                  <span class="info-label">金额</span>
                  <span class="info-value amount">¥{{ record.price }}</span>
                </div>
                <div class="order-info-row">
                  <span class="info-label">押金</span>
                  <span class="info-value deposit">¥{{ record.deposit }}</span>
                </div>
                <div class="order-info-row">
                  <span class="info-label">押金状态</span>
                  <span class="info-value">
                    <a-tag v-if="record.depositRefunded || record.status === '已退款'" color="green">已退还</a-tag>
                    <a-tag v-else-if="record.status === '已完成'" color="orange">押金未退</a-tag>
                    <a-tag v-else color="blue">冻结中</a-tag>
                  </span>
                </div>
                <div class="order-time">{{ formatDate(record.createdAt) }}</div>
              </div>
              
              <div class="order-card-actions">
                <a-button size="small" @click="viewOrder(record)">查看详情</a-button>
                <a-button 
                  v-if="record.status === '进行中'" 
                  size="small" 
                  type="primary" 
                  @click="completeOrder(record._id)"
                  :loading="completing === record._id"
                >
                  完成订单
                </a-button>
              </div>
            </div>
          </div>
          
          <div v-if="tenantOrders.length === 0 && !loading" class="empty-state">
            <a-empty description="暂无租赁订单" />
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>

    <!-- 订单详情弹窗 -->
    <a-modal
      v-model:open="orderDetailVisible"
      title="订单详情"
      width="700px"
      :footer="null"
    >
      <div v-if="selectedOrder" class="order-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="订单号">{{ selectedOrder._id }}</a-descriptions-item>
          <a-descriptions-item label="订单状态">
            <a-tag :color="getStatusColor(selectedOrder.status)">{{ selectedOrder.status }}</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="账号编号">{{ selectedOrder.account?.number }}</a-descriptions-item>
          <a-descriptions-item label="订单金额">¥{{ selectedOrder.price }}</a-descriptions-item>
          <a-descriptions-item label="押金"
          v-if="activeTab == 'tenant'"
          >¥{{ selectedOrder.deposit }}</a-descriptions-item>
          <a-descriptions-item label="押金状态"  v-if="activeTab == 'tenant'">
            <a-tag v-if="selectedOrder.depositRefunded || selectedOrder.status === '已退款'" color="green">已退还</a-tag>
            <a-tag v-else-if="selectedOrder.status === '已完成'" color="orange">押金未退</a-tag>
            <a-tag v-else color="blue">冻结中</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatDate(selectedOrder.createdAt) }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ formatDate(selectedOrder.updatedAt) }}</a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">{{ selectedOrder.remark || '无' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import orderAPI from '~/api/order'

// Props
const props = defineProps({
  // 可以添加一些配置项
})

// Emits
const emit = defineEmits(['order-updated'])

// 响应式数据
const activeTab = ref('lessor')
const loading = ref(false)
const confirming = ref(null)
const completing = ref(null)
const lessorOrders = ref([])
const tenantOrders = ref([])
const orderDetailVisible = ref(false)
const selectedOrder = ref(null)

// 出租订单列定义
const lessorColumns = [
  {
    title: '账号编号',
    dataIndex: ['account', 'number'],
    key: 'accountNumber',
    width: 110
  },
  {
    title: '金额',
    dataIndex: 'price',
    key: 'price',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150,
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 租赁订单列定义
const tenantColumns = [
  {
    title: '账号编号',
    dataIndex: ['account', 'number'],
    key: 'accountNumber',
    width: 110
  },
  {
    title: '金额',
    dataIndex: 'price',
    key: 'price',
    width: 100
  },
  {
    title: '押金',
    dataIndex: 'deposit',
    key: 'deposit',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '押金状态',
    dataIndex: 'depositStatus',
    key: 'depositStatus',
    width: 100
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
    width: 150,
    ellipsis: true
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 获取出租订单
const loadLessorOrders = async () => {
  try {
    loading.value = true
    const res = await orderAPI.getMyLessorOrders()
    if (res.code === 200) {
      lessorOrders.value = res.data.list || []
    } else {
      message.error(res.message || '获取出租订单失败')
    }
  } catch (error) {
    console.error('获取出租订单失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取租赁订单
const loadTenantOrders = async () => {
  try {
    loading.value = true
    const res = await orderAPI.getMyTenantOrders()
    if (res.code === 200) {
      tenantOrders.value = res.data.list || []
    } else {
      message.error(res.message || '获取租赁订单失败')
    }
  } catch (error) {
    console.error('获取租赁订单失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 刷新订单
const refreshOrders = () => {
  if (activeTab.value === 'lessor') {
    loadLessorOrders()
  } else {
    loadTenantOrders()
  }
}

// 标签页切换
const handleTabChange = (key) => {
  activeTab.value = key
  refreshOrders()
}

// 查看订单详情
const viewOrder = (order) => {
  selectedOrder.value = order
  orderDetailVisible.value = true
}

// 确认订单完成（出租方）
const confirmOrder = async (orderId) => {
  try {
    confirming.value = orderId
    const res = await orderAPI.setConfirmOrder(orderId)
    if (res.code === 200) {
      message.success('订单确认成功')
      emit('order-updated')
      loadLessorOrders()
    } else {
      message.error(res.message || '确认失败')
    }
  } catch (error) {
    console.error('确认订单失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    confirming.value = null
  }
}

// 完成订单（租赁方）
const completeOrder = async (orderId) => {
  try {
    completing.value = orderId
    const res = await orderAPI.setCompleteOrder(orderId)
    if (res.code === 200) {
      message.success('订单完成成功')
      emit('order-updated')
      loadTenantOrders()
    } else {
      message.error(res.message || '完成失败')
    }
  } catch (error) {
    console.error('完成订单失败:', error)
    message.error('网络错误，请稍后重试')
  } finally {
    completing.value = null
  }
}

// 申请额外费用
const applyExtraFee = (order) => {
  message.info('额外费用申请功能开发中...')
  // TODO: 实现额外费用申请逻辑
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    '待确认': 'orange',
    '进行中': 'blue',
    '已完成': 'green',
    '已取消': 'red',
    '待支付': 'gold'
  }
  return colorMap[status] || 'default'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleDateString() + ' ' + d.toLocaleTimeString()
}

// 初始化
onMounted(() => {
  loadLessorOrders()
})
</script>

<style scoped lang="scss">
.order-management {
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .order-content {

    .amount {
      color: #f5222d;
      font-weight: 600;
    }

    .empty-state {
      text-align: center;
      padding: 40px 0;
    }
  }

  .order-detail {
    .ant-descriptions {
      .ant-descriptions-item-label {
        font-weight: 500;
        color: #666;
      }
    }
  }

  :deep(.ant-table) {
    .ant-table-thead > tr > th {
      background-color: #fafafa;
      font-weight: 500;
    }

    .ant-table-tbody > tr > td {
      padding: 8px 12px;
    }
  }

  :deep(.ant-tabs) {
    .ant-tabs-nav {
      margin-bottom: 16px;
    }
  }
  
  // 默认隐藏移动端卡片
  .mobile-order-cards {
    display: none;
  }
  
  .desktop-table {
    display: table;
  }
}

// 移动端适配
@media (max-width: 768px) {
  .order-management {
    * {
      box-sizing: border-box;
    }
    .order-header {
      flex-direction: column;
      align-items: stretch;
      gap: 12px;
      margin-bottom: 16px;
      
      .ant-btn {
        width: 100%;
        height: 44px;
        font-size: 14px;
      }
    }

    :deep(.ant-tabs) {
      .ant-tabs-nav {
        margin-bottom: 12px;
        padding: 0 8px;
        
        .ant-tabs-tab {
          padding: 10px 16px;
          font-size: 14px;
          min-height: 44px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }

    // 移动端表格优化 - 改为卡片布局
    .order-content {
      .desktop-table {
        display: none !important; // 隐藏PC端表格
      }
      
      .mobile-order-cards {
        display: block; // 显示移动端卡片
      }
    }
  }
}

// 移动端卡片布局
@media (max-width: 768px) {
  .order-management .order-content {
    // 添加移动端订单卡片样式
    .mobile-order-cards {
      display: block;
      
      .order-card {
        background: #fff;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        margin-bottom: 12px;
        overflow: hidden;
        
        .order-card-header {
          background: #f8f9fa;
          padding: 12px 16px;
          border-bottom: 1px solid #e8e8e8;
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .order-id {
            font-size: 13px;
            color: #666;
            font-weight: 500;
          }
          
          .order-status {
            .ant-tag {
              margin: 0;
              font-size: 11px;
              padding: 2px 8px;
            }
          }
        }
        
        .order-card-content {
          padding: 12px 16px;
          
          .order-info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .info-label {
              font-size: 13px;
              color: #666;
              font-weight: 500;
            }
            
            .info-value {
              font-size: 13px;
              color: #333;
              font-weight: 600;
              
              &.amount {
                color: #f5222d;
                font-size: 14px;
              }
              
              &.deposit {
                color: #1890ff;
                font-size: 14px;
              }
            }
          }
          
          .order-time {
            font-size: 11px;
            color: #999;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid #f5f5f5;
          }
        }
        
        .order-card-actions {
          padding: 8px 16px;
          background: #fafafa;
          border-top: 1px solid #e8e8e8;
          display: flex;
          gap: 8px;
          
          .ant-btn {
            flex: 1;
            height: 32px;
            font-size: 12px;
            border-radius: 4px;
            
            &.ant-btn-primary {
              background: #1890ff;
            }
          }
        }
        
        &:hover {
          border-color: #1890ff;
          box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
        }
      }
    }
    
    .empty-state {
      padding: 60px 20px;
      
      :deep(.ant-empty) {
        .ant-empty-description {
          font-size: 14px;
          color: #999;
        }
      }
    }
  }
}

// 订单详情弹窗移动端适配
@media (max-width: 768px) {
  :deep(.ant-modal) {
    margin: 16px;
    max-width: calc(100vw - 32px);
    
    .ant-modal-content {
      .ant-modal-header {
        padding: 16px;
        border-bottom: 1px solid #e8e8e8;
        
        .ant-modal-title {
          font-size: 16px;
        }
      }
      
      .ant-modal-body {
        padding: 16px;
        max-height: 70vh;
        overflow-y: auto;
        
        .order-detail {
          :deep(.ant-descriptions) {
            .ant-descriptions-item {
              padding: 8px 12px;
              
              .ant-descriptions-item-label {
                font-size: 13px;
                font-weight: 500;
              }
              
              .ant-descriptions-item-content {
                font-size: 13px;
              }
            }
          }
        }
      }
      
      .ant-modal-close {
        top: 8px;
        right: 8px;
      }
    }
  }
}

// 超小屏幕适配
@media (max-width: 480px) {
  .order-management {
    * {
      box-sizing: border-box;
    }
    .order-header {
      margin-bottom: 12px;
      
      .ant-btn {
        height: 40px;
        font-size: 13px;
      }
    }
    
    :deep(.ant-tabs) {
      .ant-tabs-nav {
        padding: 0 4px;
        
        .ant-tabs-tab {
          padding: 8px 12px;
          font-size: 13px;
          min-height: 40px;
        }
      }
    }
    
    .order-content .mobile-order-cards .order-card {
      margin-bottom: 8px;
      border-radius: 6px;
      
      .order-card-header {
        padding: 10px 12px;
        
        .order-id {
          font-size: 12px;
        }
      }
      
      .order-card-content {
        padding: 10px 12px;
        
        .order-info-row {
          margin-bottom: 6px;
          
          .info-label {
            font-size: 12px;
          }
          
          .info-value {
            font-size: 12px;
            
            &.amount,
            &.deposit {
              font-size: 13px;
            }
          }
        }
        
        .order-time {
          font-size: 10px;
          margin-top: 6px;
          padding-top: 6px;
        }
      }
      
      .order-card-actions {
        padding: 6px 12px;
        
        .ant-btn {
          height: 28px;
          font-size: 11px;
        }
      }
    }
  }
}
</style> 